7. Report writing and scenario results#

ModelFlow, standard pandas routines and other python libraries like matplotlib, seaborn, plotly, and bokeh. These libraries are well-integrated with dataframes, offering seamless interaction. These packages can be used to visualize and compare dataframes generated by a model and therefore the results from scenarios – as indeed has been done in the preceding chapter.

While users are free to employ any Python-based library for visualization purposes, ModelFlow furnishes a suite of functions that build on the above packages (mainly mathplotlib), but also understand modelflow internal data structures. Moroever, they are tailored to utilize modelflow metadata such as variable descriptions and include specific transformations (like growth rates) that are useful in the analysis of macroeconomic model results.

7.1. Load model object and simulation results from Scenario Analysis Chapter#

To begin, we load the solution file that was saved at the end of the previous chapter, using the by now familiar modelload function. Because the simulations performed in the previous chapter used the keep option, and because we saved the mpakwScenarios.pcim file with the keep option set to true, we will have access to all the simulation results from the previous chapter.

mpak,_ = model.modelload(r'..\models\mpakwScenarios.pcim',run=1)
Zipped file read:  C:\modelflow manual\papers\mfbook\content\models\mpakwScenarios.pcim
mpak.keep_solutions.keys() 
dict_keys(['Baseline', '$25 increase in oil prices 2025-27', '2.5% increase in C 2025-40', '2.5% increase in C 2025-27 -- exog whole period', '2.5% increase in C 2025-27 -- exog whole period --KG=True', '2.5% increase in C 2025-27 -- temporarily exogenized', '1% of GDP increase in FDI and private investment (AF shock)'])

7.2. Table routines#

7.2.1. Display levels#

If we pass mnemonics to the model object we will get the value of the variable(s) for the time periods set in the global sample. By default the values are from the latest solution.

mpak.smpl(2023,2027) # Change global sample period to restrict output
mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN'].df
PAKNYGDPMKTPKN PAKNECONPRVTKN
2023 2.696308e+07 2.442786e+07
2024 2.739320e+07 2.481852e+07
2025 2.796323e+07 2.532326e+07
2026 2.864038e+07 2.590981e+07
2027 2.939676e+07 2.655299e+07

Alternatively we could have a larger global sample period and use with set_smpl(begin,end) to show the values of ashorter time period.

mpak.smpl(2023,2100) # Change global sample period to 2000 2100
with mpak.set_smpl(2023, 2027):
    print(mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN'].df);
      PAKNYGDPMKTPKN  PAKNECONPRVTKN
2023    2.696308e+07    2.442786e+07
2024    2.739320e+07    2.481852e+07
2025    2.796323e+07    2.532326e+07
2026    2.864038e+07    2.590981e+07
2027    2.939676e+07    2.655299e+07

Patterns can or other search parameters can be used to specify the variables to be displayed.

with mpak.set_smpl(2023, 2027):
    print(mpak['*NYGDPMKTP?N'].df)
      PAKNYGDPMKTPCN  PAKNYGDPMKTPKN  PAKNYGDPMKTPXN
2023    6.259407e+07    2.696308e+07        2.321473
2024    6.852862e+07    2.739320e+07        2.501665
2025    7.484111e+07    2.796323e+07        2.676411
2026    8.153469e+07    2.864038e+07        2.846843
2027    8.860694e+07    2.939676e+07        3.014174

If you want to look at some data from outside the current time period. you can use the dataframe and the .loc syntax. But note that this is using the dataframe ‘res; where the results were placed, not the model object: ‘mpak’.

mpak.lastdf.loc['2016':'2022','PAKNYGDPMKTPKN']
2016    2.279670e+07
2017    2.421843e+07
2018    2.461013e+07
2019    2.576058e+07
2020    2.627394e+07
2021    2.651137e+07
2022    2.668514e+07
Name: PAKNYGDPMKTPKN, dtype: float64

7.2.2. Display growth rates#

The growth rate of series can be displayed using standard pandas routines or using modelflow. Note that in the modelflow representation the growth rate for the first year is displayed whereas in the pandas routine it is not. This is because modelflow will look for lagged values outside of the active sample period, while pandas does not.

with mpak.set_smpl(2023, 2027):
    #Standard pandas way
    print(mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN'].df.pct_change()*100);
    #Modelflow way
    print(mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN'].pct.mul100.df);
      PAKNYGDPMKTPKN  PAKNECONPRVTKN
2023             NaN             NaN
2024        1.595229        1.599245
2025        2.080922        2.033686
2026        2.421581        2.316270
2027        2.640940        2.482370
      PAKNYGDPMKTPKN  PAKNECONPRVTKN
2023        1.041537        1.091432
2024        1.595229        1.599245
2025        2.080922        2.033686
2026        2.421581        2.316270
2027        2.640940        2.482370

7.2.3. Display percent change from baseline#

The modelflow methods .difpct and .mul100 can be used together to create and show a dataframe showing the percent change in a variable between the baseline and simulated scenarios.

mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN'].difpct.mul100.df  # difference in growth rates
PAKNYGDPMKTPKN PAKNECONPRVTKN
2023 0.0 0.0
2024 0.0 0.0
2025 0.0 0.0
2026 0.0 0.0
2027 0.0 0.0
... ... ...
2096 0.0 0.0
2097 0.0 0.0
2098 0.0 0.0
2099 0.0 0.0
2100 0.0 0.0

78 rows × 2 columns

7.2.4. Change the format of outputs#

In the preceding examples the formatting of outputs followed what ever the global pandas setting was. This can be changed either permanently or using a with statement.

with pd.option_context('display.float_format', '{:,.2f}'.format):
    with mpak.set_smpl(2023, 2027):
        print(mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN'].pct.mul100.df);
    
      PAKNYGDPMKTPKN  PAKNECONPRVTKN
2023            1.04            1.09
2024            1.60            1.60
2025            2.08            2.03
2026            2.42            2.32
2027            2.64            2.48

Alternatively one can use the formatted f' syntax and have one variable with one decimal places option and the second with a different one.

or the format can be changed globally pd.options.display.float_format = '{:.1f}'.format.

7.3. Graphics routines#

ModelFlow, standard pandas routines and other python libraries like matplotlib, seaborn, plotly, and bokeh. These libraries are well-integrated with dataframes, offering seamless interaction. These packages can be used to visualize and compare dataframes generated by a model and therefore the results from scenarios – as indeed has been done in the preceding chapter.

While users are free to employ any Python-based library for visualization purposes, ModelFlow furnishes a suite of functions that build encapsulate the functionality of he above packages (mainly mathplotlib), but also understand modelflow internal data structures such as variable descriptions and include specific transformations (like growth rates) that are useful in the analysis and presentation of macroeconomic data and simulation results.

  1. Plot one or more series from a single dataframe

  2. Plot one series from two (or more) dataframes, notably the .basedf and .lastdf dataframes

  3. Compare results for one or more series from the most recent simulation

    • in levels

    • differences in growth rates

    • Percent deviations from baseline levels

7.3.1. Plot one or more series from a single dataframe#

Modelflow encapsulates standard mathplotlib routines to allow you to select a series from a modelobject and graph it a range of formats.

7.3.1.1. as a level#

mpak.smpl(2020,2050)
import pandas as pd
pd.options.display.float_format = '{:.1f}'.format
_ = mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN'].plot(kind='line',title='Levels real',colrow=1,top=0.8);
../../_images/244a1caa2eee8ffb89ba92d0feaddb0dc5d973a210890e4d6649749250e2edb2.png

7.3.2. as a growth rate#

Note the temporary change to the formatting of floats for this graph only.

mpak['PAKNYGDPMKTPKN'].pct.mul100.plot(kind='line',title='Real GDP - Percent growth',colrow=1); #colrow options ensures the chart uses all of the available space
../../_images/9bd4dd9114159eed51148ae8c5c86dbc8ec32f13238efb93db9babe8cc363ee7.png

In this example the selector returns two series and the plot call generates one graph for each series.

mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN PAKNEGDIFTOTKN'].pct.\
    mul100.plot(kind='line',title='Components of GDP ',colrow=1,top=0.8); 
../../_images/5e7f63aa18a1cc78d014fde6f62eb4918cf11e1019a0ba2906c6f7e9bce98e02.png

7.3.3. Charts comparing simulation results#

Recall that the model object includes both a .basedf dataframe with the value of variables in the baseline as well as a .lastdf dataframe that contains the results from the most recent simulation.

Modeflow includes routines to display graphically the change in variables across scenarios.

7.3.3.1. First lets run a simulation#

#run a solution using the revised model and replacing the dataframe with the new one (exostart)  (that includes the exogenized variables) with their values.  Store thre results in a dataframecalled Baseline
# they will also be stored in mpak.latestdf

update_variables = {'Carbon tax on Coal (USD/Ton)'       :'PAKGGREVCO2CER',
                    'Carbon tax on Oil (USD/Ton'         :'PAKGGREVCO2OER',
                    'Carbon tax on Natural Gas (USD/Ton' :'PAKGGREVCO2GER'}
value = 29

for tax,var in update_variables.items():
        alternative_exo.loc[2020:2100,var] = value  # sets the carbon tax on all three products to value (29)
     
        
res= mpak(alternative_exo,2020,2100,alfa = 0.7,silent=1,solver = 'sim',relconv = 0.00000001) #runs the solutiona nd saves it with the name to teh left
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[15], line 10
      7 value = 29
      9 for tax,var in update_variables.items():
---> 10         alternative_exo.loc[2020:2100,var] = value  # sets the carbon tax on all three products to value (29)
     13 res= mpak(alternative_exo,2020,2100,alfa = 0.7,silent=1,solver = 'sim',relconv = 0.00000001) #runs the solutiona nd saves it with the name to teh left

NameError: name 'alternative_exo' is not defined

7.3.4. Compare results from lastest and baseline simulation#

7.3.4.1. Change in the levels#

The combination of the .dif and .plot() methods will generate a graph showing the change in the level of the variables equested

pd.options.display.float_format = '{:.1f}'.format
mpak['PAKNYGDPMKTPKN'].dif.plot(kind='line',\
                                title='Real GDP - change in levels',colrow=1,top=0.8);

7.3.4.2. Change in the growth rates of variables#

The combination of the .difpct, .mul100 and .plot() methods will generate a graph showing the change in growth rate of the variables selected. If more than one variable is selected, each change in growth rate will appear in a separate figure.

mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN '].difpct.mul100.plot(kind='line',\
                    title='Change in real growth rates',colrow=1,top=0.8);

7.3.4.3. Change in the levels expressed as a percent of GDP#

The combination of the .difpctlevel, .mul100 and .plot() methods will generate a graph showing the change in the level of the variables selected expressed as a % of the baseline (often referred to as an impulse response function). If more than one variable is selected, each impulse response function will appear in a separate figure.

mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN '].difpctlevel.mul100.plot(kind='line',\
                    title='Change in the level expressed as a percent of baseline',colrow=1,top=0.8);

7.3.5. Show baseline and simyulation results side by side on the same graph#

The .plot_alt method compares the levels or growth rates of a variable across the most recent and baseline scenarios.

with mpak.set_smpl(2020,2040):
    mpak['PAKNYGDPMKTPKN PAKNECONPRVTKN'].plot_alt("Levels, baseline versus scenario") ;

7.3.6. Plot multiple series from different scenarios#

Modelflow does not provide an out-of-the box way to compare multiple series from different scenarios, but this can be done with mathplotlib routines. In the example below the lines to be plotted are specified in separate plt.plot commands. In the first case, the line plotted is the result of a calculation done on the fly, while in the second a single variable is used.

import matplotlib.pyplot as plt

base = mpak.basedf
alt = mpak.lastdf
plt.plot(mpak.basedf.loc[2010:2050,'PAKGGBALOVRLCN']/mpak.basedf.loc[2010:2050,'PAKNYGDPMKTPCN']*100,label='Baseline')
plt.plot(mpak.lastdf.loc[2010:2050,'PAKGGBALOVRLCN_'],label='Carbon Tax scenario')
  
# set y label
plt.ylabel('% of GDP')
  
# set x label
plt.xlabel('Time')
plt.legend()  
# set title
plt.title('Overall Fiscal balance')
  
# display plot
plt.show()

7.3.7. Graphic routines for “kept” solutions#

The Keep option facilitates the comparison of results from different scenarios run on a give model object. In each of the simulations executed in the previous chapter, the keep option was activated. This caused the results from each simulation to be stored in the model object in a DataFrame that can be identified by the descriptor given to it.

7.3.7.1. Keep_solutions#

The various scenarios that have been saved in a model object are stored in a dictionary of dataframes called keep_solutions, with the keys in the dictionary being the text “names” associated with the results dataframe when the keep command was executed. To extract a list of kept solutions, one needs to display the keys of the keep_solutions dictionary.

mpak.keep_solutions.keys()  

or perhaps more easily read with:



for  key,value in mpak.keep_solutions.items():
    print(key)
    
    

The dataframes stores by the dictionary of kept solutions can be copied into temporary dataframes either for reporting purposes or in order to build a second solution on top of an initial one.

In the example below, the original baseline dataframe is assigned to a new variable oldbline and the results from the first scenario (a 25$ kike in the price of crude oil) are assigned to red_oil. Finally the change in the for GDP are expressed as a percent of the baseline GDP over the period 2024 and 2030

oldbline=mpak.keep_solutions['Baseline']
resoil=mpak.keep_solutions['$25 increase in oil prices 2025-27']

print(round((resoil.loc[2024:2030,'PAKNYGDPMKTPKN']/oldbline.loc[2024:2030,'PAKNYGDPMKTPKN']-1)*100,2))

7.3.8. The keep_variables option#

By default all variables are kept, if the user wishes to restrict the kept variables to a sub-set, they can do so by setting the keep_variables when the simulation is run, where

For example:

mpak(CTempExogAllKG,2020,2040,keep='2.5% increase in C 2025-27 -- exog whole period --KG=True',keep_variables='PAKNYGDPMKTPKN PAKNE*KN PAKEM*')

would run a simulation between 2020 AND 2040 CALLED 2.5% increase in C 2025-27 – exog whole period –KG=True but keep only the variables that matched the search string in keep_variables.

By the same token, any search criteria could be used to define the set of keep_variables, for example:

keep_variables='#MyGroup' would cause the system to retain the variables designated in that group, or keep_variables='!*invest*' would cause the system to retain the variables whose descriptions matched the search string invest.

Thus if you had specific interest in say real GDP, the current account balance and the government deficit, you might define a new Group say ReportVars as below:

mpak.var_groups['ReportVars']="PAKNYGDPMKTPKN PAKBNCABFUNDCD_ PAKGGBALOVRLCN_"

You could then store the results for these variables of interest only, by executing scenarios with keep_variables='#ReportVars' option set.

7.3.8.1. The .keep_plot() method#

The keep_plot method can be used to plot and compare results from the various scenarios that had been run earlier using the keep= option.

First lets reload the results from the simulations done in the preceding chapter where we used the keep option to save in the model object the results of a number of simulations. The results of each of those simulations can be accessed by loading the saved file that was saves earlier.

mpak,_ = model.modelload(r'..\models\mpakwScenarios.pcim', run=True)
mpak.smpl(2020,2040);

By default the results across all scenarios for each selected variables will be shown on one chart at a time (keepdim=true). NB: the 2020,2040 restricts output to the period 2020 2040 the period over which the shocks were run. Without that the graphs would display for the whole time period defined in the model object mpak.

By default each series returned by the selector (three in this instances) is rendered in a separate graph that compares results across kept scenarios.

mpak.keep_plot('PAKNYGDPMKTPCN PAKNECONPRVTKN PAKNEIMPGNFSKN',2020,2040,  legend=True,diffpct=True);
#show for each variable on a separate chart the results from each kept scenario

7.3.8.2. keep_plot() options#

options

arguments

example(s)

Explanation

pat

list of variable mnemonics or search critiera

pat=’PAKNE*KN’; pat=’#MyGroup’; pat=’PAKNYGDPMKTPKN PAKNECONPRVTKN’

Defines the variables to be retained after the simulation

start, end

a date

start=2020;end=2040

Restricts output to the time-period indicated

showtype

‘level’;’growth’;’change’

showtype=”growth”;showtype=”level”;showtype=”dif”

Displays the plot using the level, growth rate or change in the level of the variable

legend

True, False

Legend=True

True:Legend placed inside the graph; False: Legend follows each line

diff

True; False (default)

True: graphs are expressed as the difference with respect to the first scenario in the kept library

diffpct

True; False (default)

True: graphs are expressed as the percent difference with respect to the first scenario in the kept Library

Other parameters

Parameter

Type

Description

start_ofset

int

Relative offset for the start period from the current period. Defaults to 0.

end_ofset

int

Relative offset for the end period from the current period. Defaults to 0.

mul

float

Multiplier for the data. Defaults to 1.0.

title

str

Title for the plot. Defaults to ‘Show variables’.

scale

str

Scale of the plot (‘log’ or ‘linear’). Defaults to ‘linear’.

yunit

str

Units for the y-axis. Defaults to ‘’.

ylabel

str

Label for the y-axis. Defaults to ‘’.

dec

TYPE

Number of decimals to display, automated if ‘’. Defaults to ‘’.

trans

dict

Translation dictionary for variable names. Defaults to None which implies .var_description. To get the clean variable name use {}

showfig

bool

If False, the figure is not displayed. Defaults to True.

vline

list of tuples

List of (time, text) for vertical lines on the plot. To erase, delete model.vline.

keep_dim

bool

If True, each line represents a scenario; if False, each line represents a variable. Defaults to True.

dataonly

bool

If True, only the resulting data frames are returned, no plot is shown. Defaults to False.

Note

'keep_plot() returns a dictionary of Matplotlib figure objects, with keys being the variable names. return a python object that points to the in memory version of the rendered figure(s). The values can be used to modify the graph (see examples towards the end of this chapter).

7.3.8.2.1. An example using the diff=True option#

When diff=True (or 1) results from all kept scenarios will be presented as the level change in selected variables with respect to the first scenario in the keep list. – in this instance the scenario saved with the name baseline (for memory these are stored in the dictionrary keep_solutions and can be visualized with the code snippet below).

for  key,value in mpak.keep_solutions.items():
    print(key)

Warning

Note in this instance baseline and basedf are the same because they were defined that way. However, there is nothing in the system that guarantees that the first keep scenario will be the baseline or the basedf scenario.

#Set the default period for the mpak object to 2020 2040
# because of this future calls to keep_plot or anyother model objkect method
# will operate over the period 2020 2040 only.
mpak.smpl(2020,2040) 
mpak.keep_plot('PAKNYGDPMKTPCN PAKNEIMPGNFSKN', diff=1, legend=True);
7.3.8.2.2. The showtype option#

In this example the difference with respect first 'keep scenario baseline values are once again shown. This time the showtype option has been set to growth. As a result the data is displayed as the difference in the growth rates between the simulation scenarios and the growth rate in the baseline scenario – remembering that keep_plot is calculating the differences with respect to the first kept scenario. Its name need not have been baseline, this was just a decision made in preparing the shocks that facilitated the kind of comparisons to be displayed.

mpak.keep_plot('PAKNYGDPMKTPCN PAKNEIMPGNFSKN', diff=1,showtype='growth', legend=True);
7.3.8.2.3. The diffpct option#

Setting diffpct=True instructs .keep_plot() to display the data as a percent deviation from the first kept scenario, which in this case was the baseline scenario. \(\big(\frac{x_{shock}-x_{original}}{x_{shock}}\big) * 100\)

mpak.keep_plot('PAKNYGDPMKTPCN  PAKNEIMPGNFSKN', diffpct=True,showtype='level',legend="Change in level as a % of first keep scenario");

7.3.8.3. The .keep_switch() method#

The .keep_switch() method restricts the number of scenarios on which subsequent calls to .keep_plot() (and .keep_plot_multi()) are executed on. .keep_switch() can be passed a list of scenarios or using a wildcard selector.

7.3.8.3.1. The .keep_solutions.keys() method#

The .keep_solutions.keys() method displays a list of the solutions that have been kept previously.

mpak.keep_solutions.keys()

To specify exactly which scenarios to show in a keep_plot, the scenarios= option of .keepswitch() must be initialized with a “|” delimited string of the names of the scenarios (retrieved above) that are to be displayed.

By placing the .keepswitch() in a with clause the scenario restriction will only apply to indented lines that follow the with construct.

As before the scenarios are compared with the first scenario in the keep dictionary, which in this instance happens to be named ‘baseline’.

with mpak.keepswitch(scenarios='2.5% increase in C 2025-40|2.5% increase in C 2025-27 -- exog whole period|2.5% increase in C 2025-27 -- exog whole period --KG=True|2.5% increase in C 2025-27 -- temporarily exogenized'):
    mpak.keep_plot('PAKNYGDPMKTPKN PAKGGBALOVRLCN PAKGGDEBTTOTLCN',start=2020,end=2040,diff=False,showtype='growth',legend=True);
7.3.8.3.2. keep_plot with keep_dim=False#

When Keep_dim is set to False keep_plot shows all pf the selected variables for each scenario on a single chart (rather than the default behavior of the results for each variable across the various scenarios on one plot.

with mpak.keepswitch(scenarios='2.5% increase in C 2025-40|2.5% increase in C 2025-27 -- exog whole period'):
    mpak.keep_plot('PAKNYGDPMKTPKN PAKGGBALOVRLCN PAKGGDBTTOTLCN',start=2020,end=2040,diff=False,showtype='growth',legend=True,keep_dim=False);
7.3.8.3.3. The .keep_solutions.keys() method with diff=True#

If .keep_plot() is called on a sub-set of the kept solutions, the comparison will be made relative to the first scenario in the .keep_switch call.

Thus in the example below (which repeats the previous call, but sets diff=True, all of the shocks are calculated relative to the shock named ‘2.5% increase in C 2025-40’. Thus there are only three lines (not four as when diff=False).

with mpak.keepswitch(scenarios='2.5% increase in C 2025-40|2.5% increase in C 2025-27 -- exog whole period|2.5% increase in C 2025-27 -- exog whole period --KG=True|2.5% increase in C 2025-27 -- temporarily exogenized'):
    mpak.keep_plot('PAKNYGDPMKTPKN PAKGGBALOVRLCN ',start=2020,end=2040,diff=True,showtype='growth',legend=True);

If, as before, the objective was to compare the four scenarios with the baseline scenario, the baseline scenario would have to be added to the .keep_switch() call as below:

with mpak.keepswitch(scenarios='baseline|2.5% increase in C 2025-40|2.5% increase in C 2025-27 -- exog whole period|2.5% increase in C 2025-27 -- exog whole period --KG=True|2.5% increase in C 2025-27 -- temporarily exogenized'):
    mpak.keep_plot('PAKNYGDPMKTPKN PAKGGBALOVRLCN PAKGGDBTTOTLCN',start=2020,end=2040,diff=True,showtype='growth',legend=True);

Warning

.keep_switch() and .keep_plot() with option diff=True

When the .keep_plot() option diff is set to True, the figures will be generated as comparisons with the values of the first scenario specified in the .keep_switch() command. In most instances users will want to use the baseline scenario as this comparison point. Failure to do so when this was the intention/expectation of the user, will generate unexpected results.

7.3.8.4. Keepswitch with wildcard selection#

Below a series of plots are generated using a wildcard selector in the keepswitch clause.

with mpak.keepswitch(scenarios='*2025*'):
    mpak.keep_plot('PAKNYGDPMKTPKN PAKNECONPRVTKN',showtype='growth',legend=True,start=2020,end=2040);

7.3.8.5. .keep_plot() with samefig=True#

The samefig=True method allows several charts to be displayed in a grid. The size of each chart can be set with the size=(w,h) option, where the units of width and height are in inches.

Then samefig=True is used. keep_plot() will return a dictionary with only one key which is 'onefig'

The parameters ncol and size can be used to get the desired visual expression.

Argument

Description

Default

ncol

Number of columns for subplots when using samefig.

2

size

Figure size as (width, height).

(10, 6)

Also note that the parameters ncol with default value of 2 and size

Also if legend=1 The legend will only be shown once - at the bottom of the charts

7.3.8.6. .keep_plot with keep_dim=False#

with mpak.keepswitch(scenarios='*2025*'):
    mpak.keep_plot('PAKNYGDPMKTPKN PAKNECONPRVTKN',showtype='growth',legend=True,start=2020,end=2040
                  ,samefig=True);

7.3.9. Modifying figure objects#

As indicated earlier keep_plot() return a dictionary containing either:

  • if samefig=False A matplotlib figure object for each variable.

  • if samefig=False One matplotlib figure object with a grid of charts for all the variable.

The content of the dictionary can be used to embellish or modify the figures produced by the automatic routines.

The command

var_figs = mpak.keep_plot_multi('PAKNYGDPMKTPKN PAKNECONPRVTKN PAKNEGDIFTOTKN PAKNEIMPGNFSKN PAKNEEXPGNFSKN',2010,2040,keep_dim=0,
            legend=1,size=(20,20) ,diffpct=True,title='Scenario Comparison'  );

returns several figures placed into a grid, which in this case is assigned to a pytyhon object var_figs. This contains a matrix (grid) of mathplotlib figures can then be manipulated using standard mathplotlib commands.

with mpak.set_smpl(2000,2040):
    with mpak.keepswitch(scenarios="baseline *exog*"):
        var_figs = mpak.keep_plot('PAKNYGDPMKTPKN PAKNECONPRVTKN PAKNEGDIFTOTKN PAKNEIMPGNFSKN PAKNEEXPGNFSKN',2010,2040,keep_dim=0,legend=1
                                ,samefig=1 ,
                                  diffpct=True,title='Scenario Comparison'  );

7.3.9.1. Change the size of charts#

var_fig = var_figs['onefig']
var_fig.set_size_inches(20,15)
var_fig

Individual charts can be deleted from the grid.

Note

The grid representation of the individual charts is returned as a 0-based vector of charts. Thus the first figure is the zeroeth and the second is the first.

7.3.10. Delete a chart from the grid#

A chart can be deleted from the grid by referencing it and calling the .remove() method.

In this example the second chart (index number 1) has been removed.

var_fig.axes[1].remove()
var_fig

The same mechanism can be used to revise the titles of the indidividual charts and annotate them.

var_fig.axes[0].set_title('Impact of a 2.5% increase in C using exog method');    # many properties can be set afterward 
var_fig.axes[1].set_title('Impact of a 2.5% increase in C using temporary exog method');
var_fig
var_fig.axes[0].set_xlabel('Year')
var_fig.axes[0].set_ylabel('Change percent\nchange in level',fontsize=10)
var_fig.axes[0].yaxis.set_label_coords(-0.1,1.02)
var_fig.axes[0].xaxis.set_label_coords(.95,-.06)
var_fig

Variables pointing to the individual charts can be defined and used to make modifications to individual charts within the overall figure.

ax0=var_fig.axes[0]
ax1=var_fig.axes[1]
ax1.set_ylabel('Percent change\nin level',fontsize=10)
ax1.yaxis.set_label_coords(-0.1,1.02) #place axes labels
ax1.xaxis.set_label_coords(.95,-.06)



ax1.text(2030.,1.4, 'Some text in a box', 
          color='yellow',bbox=dict(facecolor='red', alpha=0.5));
ax1.text(2035.,-1., 'More text', 
          style='italic',color='green');
          
var_fig
          

7.3.11. Save plots as files.#

The .savefigs function is used to save the plots for publication or other later use:

Parameter

Type

Default

Description

figs

dict

-

A dictionary of matplotlib figures where the key is the figure name.

location

str

‘./graph’

The base folder in which to save the charts.

experimentname

str

‘experiment1’

A subfolder under ‘location’ where charts are saved.

addname

str

‘’

An additional name added to each figure filename.

extensions

list

[‘svg’]

A list of string file extensions for saving the figures.

xopen

bool

True

If True, open the saved figure locations in a web browser.

It will return the location where the files are saved

mpak.savefigs(var_figs,extensions=['pdf','png'],xopen=False);

7.4. Interactive widgets#

Modelflow running in a Jupyter Notebook includes two interactive widgets that reproduce much of the functionality described above.

The main widget pertains to all modelflow model objects and is called

mpak['#Headline'] #display a widget for all the variables defined in the headline group

or
mpak['PAK*EMIS*'] #display a widget of all the emission variables

The widget by definition will show tables and graphs for the value and growth rates of the requested variables from both the .basedf and .latestdf and latest, as well as their differences, differences in growth rates, pecent change in levels/

mpak['#Headline']
mpak['PAK*EMIS*']

7.4.1. .keep_show() Interactive widget for keep_plot#

The .keep_show() method does preapres similar outputs for simulations that have been stored via the keep option.

.keep_show()

This will show a interactive widget which allows the user to design scenario charts as shown below.

mpak.keep_show(legend=1) 
Menu to start notebooks in subfolders

7.4.2. Save charts to file.#

When the Allow save to file checkbox is checked, an additional widget is displayed. This can be used to save the charts in a number of formats. As a default the charts are saved in graph/experiment name.

7.4.3. savefig method#

The savfig method is a standard mathplotlib method that can be used to sabe a figure using a range of different formats.

Menu to start notebooks in subfolders

7.4.4. Settings#

There are a number of settings which allows the user to customize the inputs required by the widget.

Parameter

Type

Description

smpl

Tuple

The selected sample, a tuple with 2 elements, matching the dataframe index. Defaults to (‘’,’’).

use_smpl

False

Show a sample selection slider.

selectfrom

List

The variables to select from. Defaults to [] (all kept variables).

legend

False

Show legends or to the right of the curve.

dec

String

Decimals on the y-axis. Defaults to ‘0’.

use_descriptions

True

Use the variable descriptions from the model.

vline

List

List of vertical lines (position, text).

add_var_name

False

Add the variable name to description.

short

0, 1 or 2

Short, 1 or 2 cut down on the input fields.

select_scenario

True

Allow selection of scenarios for which charts are displayed.

switch

False

Use the scenarios in mmodel.basedf and mmodel.lastdf.

var_groups

Dict

A dictionary of variable patterns to select, e.g., countries.

use_var_groups

True

Use the var_groups.

displaytype

String

Display type, one of [‘tab’, ‘accordion’, ‘anything’].

save_location

String

Default save location.

relativ_start

Int

Relative start.

selected

String

Selected item.

select_width

String

Width of the selection widget.

select_height

String

Height of the selection widget.

7.4.5. .keep_show() call with options#

The following shows a call when the most used options has been set explicitly. If a parameter is not set explicitly the default will be used.

mpak.keep_show(
select_scenario = True,  # default = False, allow selection of scenarios to display 
use_smpl        = True,  # default = False, allow selection of display smpl 
use_descriptions= True, # default = True,  use descriptions from model  
add_var_name    = False, # default = False, add variable name to description
switch          = False, # default = False, use basedf and lastdf as scenarios
use_var_groups  = True,  # default = True, show selection menu based on var_groups 
var_groups      = mpak.var_groups,  # default = .var_groups Grouping of variable to be used.
selectfrom     = 'PAK*',  # default = '*' Select variables  
legend         = True, # Default= False show legend     
)